package com.neutech.shop.service.impl;

import com.neutech.shop.entity.ConditionVO;
import com.neutech.shop.entity.Product;
import com.neutech.shop.mapper.ProductMapper;
import com.neutech.shop.service.ProductService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @author Neuedu-远哥
 * @version 1.0
 * @date 2021/9/29 10:41
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper mapper;

    @Override
    public List<Product> findAll() {
        return mapper.selectAll();
    }

    @Override
    public void insert(Product product, CommonsMultipartFile file, HttpServletRequest request) {
        // 实际业务中，要进行文件上传（复制的过程）
        // 1. 文件拷贝
        // 1.txt -> .txt 处理文件名称
        String fileAllName = file.getOriginalFilename();
        String tomcatPath = request.getServletContext().getRealPath("/") + "/images/" +
                UUID.randomUUID().toString().replace("-","") + fileAllName.substring(fileAllName.lastIndexOf("."));

        // 程序自动创建文件夹
        File f1 = new File(tomcatPath);

        // 获取当前文件对象的父级路径
        File parentFile1 = f1.getParentFile();

        // 如果有，直接上传，如果没有，创建文件夹
        if(!parentFile1.exists()){
            parentFile1.mkdir();
        }
        try {
            file.transferTo(f1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(tomcatPath);
        String imagePath = "/images" + tomcatPath.substring(tomcatPath.lastIndexOf("/"));
        product.setImgPath(imagePath);
        // 2. 存入数据库
        mapper.insert(product);

    }

    @Override
    public List<Product> selectByKeywords(String keywords) {
        return mapper.selectByKeywords(keywords);
    }

    @Override
    public List<Product> searchProductComplex(ConditionVO conditionVO) {
        return mapper.searchProductComplex(conditionVO);
    }

    @Override
    public List<Product> lastedProduct(int startIndex) {
        return mapper.lastedProduct(startIndex);
    }

    @Override
    public Product selectById(Integer id) {
        return mapper.selectById(id);
    }
}
